// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({env: 'evn-cloud-a-4gf1q6iy9df62d73'})
const db = cloud.database()
const $ = db.command.aggregate
const MAX_LIMIT = 100

const numberFormat = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
const getCurrentDate = () =>{
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const dateStr = `${[year, month, day].map(numberFormat).join('-')}`
  return dateStr
}

/**生成当日放生名单 */
const generateTodayFreeCaptiveList = async () => {
  //根据名单查出每位功德主最近的余额，即为新生成放生名单的余额
  const query = db.collection('kindPersonList').where({})
  const countResult = await query.count()
  const totalCount = countResult.total
  const batchTimes = Math.ceil(totalCount / 100)
  console.log('功德主名单数据总条数为: ', totalCount, '全部取出需要循环的次数为: ', batchTimes)
  let tasks = []
  for (let i = 0; i < batchTimes; i++) {
    const promise = await query.skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    tasks.push(promise)
  }
  if(tasks.length == 0){ return {data: undefined, errMsg: '查询结果为空'} }
  // 等待所有
  const kindPeopleLis = (await Promise.all(tasks)).reduce((acc, cur) => {return { data: acc.data.concat(cur.data), errMsg: acc.errMsg}})
  const list = kindPeopleLis.data
  for(let i=0; i < list.length; i++){
    console.log('\n\n开始添加数据，姓名：',list[i].meritsVirtues,'日期： ', getCurrentDate())
    const promise = await db.collection("freeCaptiveDetails").where({meritsVirtues: list[i].meritsVirtues}).orderBy('freeDate',"desc").limit(1).get({})
    const data = promise.data
    let balance = 0
    //放生明细表中，无论之前存不存在此功德主，都生成今日明细
    if(data != null && data.length > 0){ 
      balance = Number(data[0].balance)
    }
    const curDate = await getCurrentDate();
    //如果this功德主今日已存在，则直接返回，若不存在，添加
    const queryFreeCapResult = await db.collection('freeCaptiveDetails').where({meritsVirtues: list[i].meritsVirtues, freeDate: curDate}).get({})
    console.log('查询放生明细表结果为：',queryFreeCapResult.data)
    if(queryFreeCapResult.data != null && queryFreeCapResult.data.length > 0){
      console.warn('姓名：'+list[i].meritsVirtues+'，日期：' + getCurrentDate() + '，已在放生明细表中有数据，无需重复生成.')
      continue;
    }
    const addResult = await db.collection("freeCaptiveDetails").add({ data:{ meritsVirtues: list[i].meritsVirtues, freeDate: curDate, freeAmount: 0, balance: balance, isSelect: false}})
    console.log('生成名单返回结果(addResult)的值:',addResult)
    if(addResult._id){
      console.info('姓名：'+list[i].meritsVirtues+'，日期：' + getCurrentDate() + '，生成名单成功.')
    }else {
      console.info('姓名：'+list[i].meritsVirtues+'，日期：' + getCurrentDate() + '，生成名单失败.')
    }
    console.log("开始下一条。\n\n")
  }
}

// 云函数入口函数
exports.main = async (event, context) => {
  console.log('生成今日放生名单.\n')
  await generateTodayFreeCaptiveList()
  return '定时任务执行成功.\n'
}